<template>
  <div id="demo" class="clearfix">
    <!-- 遮罩层 -->
    <div class="containers" v-show="panel">
      <div>
        <img id="image" :src="url" alt="Picture">
      </div>
    </div>
    <!-- 预览 -->
    <div class="preview">
      <div class="biggest">
        <div class="previews default" v-if="headImg">
          <img :src="headImg" alt=".">
        </div>
        <div class="previews" v-else>
          <i class="icon-personal-default"></i>
        </div>
      </div>
      <div class="medium">
        <div class="previews default" v-if="headImg">
          <img :src="headImg" alt="">
        </div>
        <div class="previews" v-else>
          <i class="icon-personal-default"></i>
        </div>
      </div>
      <div class="minimum">
        <div class="previews default" v-if="headImg">
          <img :src="headImg" alt="">
        </div>
        <div class="previews" v-else>
          <i class="icon-personal-default"></i>
        </div>
      </div>
      <div class="uploadBtn">
        <button class="clickUpLoad" :class="{rate: !uploading}">{{reUploadBtnText}}</button>
        <input type="file" id="change" accept="image" @change="change" ref="fileInp">
        <label for="change"></label>
      </div>
    </div>
    <!-- 最终效果 -->
    <div>
      <div class="show">
        <div class="border" v-if="!headImg">
          <i class="icon-personal-default"></i>
        </div>
        <div class="picture" v-else :style="'backgroundImage:url('+headerImage+')'"></div>
      </div>
    </div>
  </div>
</template>

<script>
import Cropper from 'cropperjs'
import eventBus from '../../../apis/bus'  // 引入bus

let blob = ''

export default {
  name: 'cropper',
  props: ['headImg', 'reUploadBtnText', 'uploading'],
  data () {
    return {
      headerImage: this.headImg,
      picValue: '',
      cropper: '',
      croppable: false,
      panel: false,
      url: ''
    }
  },
  mounted () {
    // 初始化这个裁剪框
    let self = this
    let image = document.getElementById('image')
    let previews = document.querySelectorAll('.previews')
    this.cropper = new Cropper(image, {
      aspectRatio: 1,
      viewMode: 1,
      background: false,
      zoomable: false,
      ready: function () {
        self.croppable = true
        let clone = this.cloneNode()
        clone.className = ''
        clone.style.cssText = (`display: block; width: 100%; min-width: 0; min-height: 0; max-width: none; max-height: none;`)
        self.each(previews, function (elem) {
          elem.appendChild(clone.cloneNode())
        })
      },
      crop: (e) => {
        let data = e.detail
        let cropper = self.cropper
        let imageData = cropper.getImageData() // 输出图像位置，大小等相关数据。
        let previewAspectRatio = data.width / data.height
        self.each(previews, function (elem) {
          let previewImage = elem.getElementsByTagName('img').item(0)
          let previewWidth = elem.offsetWidth
          let previewHeight = previewWidth / previewAspectRatio
          let imageScaledRatio = data.width / previewWidth
          elem.style.height = previewHeight + 'px'
          try {
            previewImage.style.width = imageData.naturalWidth / imageScaledRatio + 'px'
            previewImage.style.height = imageData.naturalHeight / imageScaledRatio + 'px'
            previewImage.style.marginLeft = -data.x / imageScaledRatio + 'px'
            previewImage.style.marginRight = -(imageData.naturalWidth / imageScaledRatio - data.x / imageScaledRatio) + 'px'
            previewImage.style.marginTop = -data.y / imageScaledRatio + 'px'
            previewImage.style.marginBottom = -(imageData.naturalHeight / imageScaledRatio - data.y / imageScaledRatio) + 'px'
          } catch (e) {
            console.log(e)
          }
        })
      }
    })
  },
  watch: {
    'headImg' (val) {
      if (val) {
        this.headerImage = val
      }
    }
  },
  methods: {
    getObjectURL (file) {
      let url = null
      if (window.createObjectURL !== undefined) { // basic
        url = window.createObjectURL(file)
      } else if (window.URL !== undefined) { // mozilla(firefox)
        url = window.URL.createObjectURL(file)
      } else if (window.webkitURL !== undefined) { // webkit or chrome
        url = window.webkitURL.createObjectURL(file)
      }
      return url
    },
    change (e) {
      let previews = document.querySelectorAll('.previews')
      previews.forEach(item => {
        item.innerHTML = ''
      })
      let files = e.target.files || e.dataTransfer.files
      if (!files.length) return
      this.panel = true
      this.picValue = files[0]

      this.url = this.getObjectURL(this.picValue)
      // 每次替换图片要重新得到新的url
      if (this.cropper) {
        this.cropper.replace(this.url)
      }
      this.panel = true
    },
    crop () {
      this.panel = false
      let croppedCanvas
      let roundedCanvas
      if (!this.croppable) {
        return
      }
      // Crop
      croppedCanvas = this.cropper.getCroppedCanvas()
      // Round
      roundedCanvas = this.getRoundedCanvas(croppedCanvas)

      this.headerImage = roundedCanvas.toDataURL()
      blob = this.dataURLtoBlob(roundedCanvas.toDataURL())
      this.postImg(blob)
    },
    getRoundedCanvas (sourceCanvas) {
      let canvas = document.createElement('canvas')
      let context = canvas.getContext('2d')
      let width = sourceCanvas.width
      let height = sourceCanvas.height
      canvas.width = width
      canvas.height = height
      context.imageSmoothingEnabled = true
      context.drawImage(sourceCanvas, 0, 0, width, height)
      context.globalCompositeOperation = 'destination-in'
      context.beginPath()
      context.arc(width / 2, height / 2, Math.min(width, height) / 2, 0, 2 * Math.PI, true)
      context.fill()
      return canvas
    },
    postImg (blob) {
      // 这边写图片的上传
      eventBus.$emit('postImg', blob)
    },
    // base64 转图片对象
    dataURLtoBlob (dataurl) {
      let arr = dataurl.split(',')
      let mime = arr[0].match(/:(.*?);/)[1]
      let bstr = atob(arr[1])
      let n = bstr.length
      let u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new Blob([u8arr], {
        type: mime
      })
    },
    // 展示预览图
    each (arr, callback) {
      let length = arr.length
      let i
      for (i = 0; i < length; i++) {
        callback.call(arr, arr[i], i, arr)
      }
      return arr
    }
  },
  beforeDestroy () {
    let previews = document.querySelectorAll('.previews')
    previews.forEach(elem => {
      elem.getElementsByTagName('img').item(0) && (elem.getElementsByTagName('img').item(0).src = '')
    })
  }
}
</script>

